<template>
  <div class="employee-page">
    <div class="page-header">
      <div class="title">员工管理</div>
      <div class="desc">员工是餐厅的核心资产，合理管理员工账号和权限</div>
    </div>

    <div class="content-card">
      <div class="search-bar">
        <div class="search-item">
          <span>员工姓名：</span>
          <el-input
            v-model="searchQuery"
            placeholder="请输入员工姓名"
            class="search-input"
            clearable
          >
          </el-input>
        </div>
        <el-button type="primary" @click="handleSearch" class="search-btn">
          查询
        </el-button>
        <el-button type="info" @click="handleRefresh" class="refresh-btn">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="handleAdd" class="add-btn">
          + 添加员工
        </el-button>
      </div>

      <el-table 
        :data="employeeList" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{background:'#f8f8f9', color: '#333', fontWeight: 'bold'}"
        :row-class-name="tableRowClassName"
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="员工姓名" min-width="100">
          <template #default="{row}">
            <span class="employee-name">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" min-width="100" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="status" label="账号状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="light" size="small">
              <i :class="row.status === 1 ? 'el-icon-check' : 'el-icon-close'" class="status-icon"></i>
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" min-width="160">
          <template #default="{row}">
            <div class="time-info">
              <el-icon><Timer /></el-icon>
              <span>{{ row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280" align="center">
          <template #default="{ row }">
            <div class="operation-btns">
              <el-tooltip 
                :content="isAdminUser(row) ? '管理员账户不可修改' : '编辑员工'" 
                placement="top" 
                :show-after="300"
              >
                <el-button 
                  type="primary" 
                  link 
                  @click="handleEdit(row)" 
                  class="op-button"
                  :disabled="isAdminUser(row)"
                >
                  <el-icon><Edit /></el-icon>
                  <span>修改</span>
                </el-button>
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-tooltip 
                :content="isAdminUser(row) ? '管理员账户不可重置密码' : '重置密码'" 
                placement="top" 
                :show-after="300"
              >
                <el-button 
                  type="primary" 
                  link 
                  @click="handleResetPassword(row)" 
                  class="op-button"
                  :disabled="isAdminUser(row)"
                >
                  <el-icon><Key /></el-icon>
                  <span>密码</span>
                </el-button>
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-tooltip 
                :content="isAdminUser(row) ? '管理员账户不可禁用' : (row.status === 1 ? '禁用账号' : '启用账号')" 
                placement="top" 
                :show-after="300"
              >
                <el-button 
                  type="primary" 
                  link 
                  :class="row.status === 1 ? 'op-button-danger' : 'op-button'"
                  @click="handleToggleStatus(row)"
                  :disabled="isAdminUser(row)"
                >
                  <el-icon>
                    <Check v-if="row.status === 0" />
                    <Close v-else />
                  </el-icon>
                  <span>{{ row.status === 1 ? '禁用' : '启用' }}</span>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <span>共 {{ total }} 条</span>
        <el-select v-model="pageSize" class="page-size-select" @change="handleSizeChange">
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
          <el-option :value="30" label="30条/页" />
          <el-option :value="40" label="40条/页" />
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          background
        />
        <span>前往 <el-input v-model="jumpPage" class="jump-page" @keyup.enter="handleJumpPage" /> 页</span>
      </div>
    </div>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      width="500px"
      custom-class="employee-dialog"
      destroy-on-close
    >
      <template #header>
        <div class="dialog-header">
          <el-icon @click="dialogVisible = false" class="back-icon">
            <ArrowLeft />
          </el-icon>
          <span>{{ isEdit ? '编辑员工' : '添加员工' }}</span>
        </div>
      </template>
      <el-form
        :model="employeeForm"
        :rules="rules"
        ref="employeeFormRef"
        label-width="80px"
        class="employee-form"
        label-position="top"
      >
        <el-form-item label="账号:" prop="username" v-if="!isEdit">
          <el-input v-model="employeeForm.username" placeholder="请输入账号">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="员工姓名:" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入员工姓名">
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入手机号">
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="employeeForm.sex">
            <el-radio :label="1">
              <el-icon><Male /></el-icon> 男
            </el-radio>
            <el-radio :label="0">
              <el-icon><Female /></el-icon> 女
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="employeeForm.idNumber" placeholder="请输入身份证号">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="warning" @click="saveAndContinue">保存并继续添加</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="重置密码"
      width="500px"
      destroy-on-close
    >
      <div class="dialog-content">
        <el-alert
          title="将为该员工设置新密码"
          type="warning"
          :closable="false"
          show-icon
          class="pwd-alert"
        >
          <template #default>
            <div class="alert-content">
              <p><strong>员工:</strong> {{ currentEmployee?.name }}</p>
              <p><strong>账号:</strong> {{ currentEmployee?.username }}</p>
            </div>
          </template>
        </el-alert>
        
        <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordFormRef"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              placeholder="请输入新密码" 
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入新密码" 
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import employeeApi from '@/api/employee' // 引入新的员工API模块
import { ArrowLeft, Edit, Check, Close, Document, User, UserFilled, Iphone, Key, Male, Female, Timer, Refresh } from '@element-plus/icons-vue'

// 员工列表数据
const employeeList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpPage = ref('')
const searchQuery = ref('')
const loading = ref(false)

// 员工表单数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const employeeForm = reactive({
  id: null,
  username: '',
  name: '',
  phone: '',
  sex: 1,
  idNumber: ''
})
const employeeFormRef = ref(null)

// 密码表单数据
const passwordDialogVisible = ref(false)
const passwordForm = reactive({
  id: null,
  empId: null,
  newPassword: '',
  confirmPassword: ''
})
const passwordFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
})

// 密码表单验证规则
const passwordRules = reactive({
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
})

// 获取员工列表
const getEmployeeList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    if (searchQuery.value) {
      params.name = searchQuery.value
    }
    
    const res = await employeeApi.getEmployeeList(params)
    if (res.code === 1) {
      employeeList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getEmployeeList()
}

// 刷新
const handleRefresh = () => {
  searchQuery.value = ''
  currentPage.value = 1
  getEmployeeList()
}

// 添加员工
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  isEdit.value = true
  
  try {
    const res = await employeeApi.getEmployeeById(row.id)
    if (res.code === 1) {
      // 确保性别为数字类型
      const employeeData = { ...res.data }
      if (employeeData.sex !== undefined) {
        employeeData.sex = Number(employeeData.sex)
      }
      Object.assign(employeeForm, employeeData)
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取员工详情失败:', error)
    ElMessage.error('获取员工详情失败')
  }
}

// 重置密码
const handleResetPassword = (row) => {
  passwordForm.id = row.id
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 启用/禁用员工账号
const handleToggleStatus = (row) => {
  const statusText = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${statusText}「${row.name}」的账号吗？`,
    `${statusText}账号`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const newStatus = row.status === 1 ? 0 : 1
      const res = await employeeApi.updateStatus(row.id, newStatus)
      if (res.code === 1) {
        ElMessage.success(`${statusText}成功`)
        getEmployeeList()
      }
    } catch (error) {
      console.error(`${statusText}账号失败:`, error)
      ElMessage.error(`${statusText}账号失败`)
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const apiMethod = isEdit.value ? employeeApi.updateEmployee : employeeApi.addEmployee
        const res = await apiMethod(employeeForm)
        if (res.code === 1) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getEmployeeList()
        }
      } catch (error) {
        console.error(isEdit.value ? '修改员工失败:' : '添加员工失败:', error)
        ElMessage.error(isEdit.value ? '修改员工失败' : '添加员工失败')
      }
    }
  })
}

// 保存并继续添加
const saveAndContinue = async () => {
  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const apiMethod = isEdit.value ? employeeApi.updateEmployee : employeeApi.addEmployee
        const res = await apiMethod(employeeForm)
        if (res.code === 1) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          if (!isEdit.value) {
            resetForm()
            employeeFormRef.value.clearValidate()
            getEmployeeList()
          } else {
            dialogVisible.value = false
            getEmployeeList()
          }
        }
      } catch (error) {
        console.error(isEdit.value ? '修改员工失败:' : '添加员工失败:', error)
        ElMessage.error(isEdit.value ? '修改员工失败' : '添加员工失败')
      }
    }
  })
}

// 提交密码表单
const submitPasswordForm = async () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await employeeApi.updatePassword({
          empId: passwordForm.id,
          newPassword: passwordForm.newPassword
        })
        if (res.code === 1) {
          ElMessage.success('重置密码成功')
          passwordDialogVisible.value = false
        }
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      }
    }
  })
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 1 ? 'row-even' : 'row-odd'
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getEmployeeList()
}

// 每页条数改变
const handleSizeChange = () => {
  currentPage.value = 1
  getEmployeeList()
}

// 页码跳转
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (isNaN(pageNum) || pageNum < 1 || pageNum > Math.ceil(total.value / pageSize.value)) {
    ElMessage.warning('请输入有效的页码')
    return
  }
  currentPage.value = pageNum
  getEmployeeList()
}

// 重置表单
const resetForm = () => {
  Object.assign(employeeForm, {
    id: null,
    username: '',
    name: '',
    phone: '',
    sex: 1,
    idNumber: ''
  })
}

// 生命周期
onMounted(() => {
  getEmployeeList()
})

// 添加管理员权限判断
const isAdminUser = (row) => {
  // 判断是否为管理员账户：用户名为admin或ID为1
  return row.username === 'admin' || row.id === 1
}
</script>

<style scoped>
.employee-page {
  background: #f5f7fa;
  min-height: calc(100vh - 50px);
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header .title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.page-header .desc {
  font-size: 14px;
  color: #666;
}

.content-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.search-input {
  width: 200px;
}

.search-btn {
  margin-right: 10px;
}

.refresh-btn {
  margin-right: 10px;
}

.add-btn {
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.page-size-select {
  margin: 0 10px;
  width: 100px;
}

.jump-page {
  width: 50px;
  margin: 0 5px;
}

.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 0;
  padding: 20px 20px 10px;
}

.back-icon {
  margin-right: 10px;
  cursor: pointer;
  font-size: 18px;
}

.dialog-header span {
  font-size: 18px;
  font-weight: bold;
  flex: 1;
}

.employee-form .el-form-item__label::before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.employee-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 0;
  border-bottom: 1px solid #f0f0f0;
}

.employee-dialog :deep(.el-dialog__body) {
  padding-top: 20px;
}

/* 表格行样式 */
:deep(.row-even) {
  background-color: #fafafa;
}

:deep(.row-odd) {
  background-color: #fff;
}

:deep(.el-table th) {
  font-weight: bold !important;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa !important;
}

/* 员工信息样式 */
.employee-info {
  display: flex;
  align-items: center;
}

.employee-name {
  margin-left: 10px;
  font-weight: 500;
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  justify-content: center;
  align-items: center;
}

.op-button {
  color: #409EFF;
  display: flex;
  align-items: center;
}

.op-button-danger {
  color: #F56C6C;
  display: flex;
  align-items: center;
}

.op-button i, .op-button-danger i {
  margin-right: 4px;
}

/* 禁用按钮样式 */
.op-button:disabled,
.op-button-danger:disabled {
  color: #C0C4CC !important;
  cursor: not-allowed !important;
}

.op-button:disabled span,
.op-button-danger:disabled span {
  color: #C0C4CC !important;
}

/* 时间信息样式 */
.time-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.time-info i {
  margin-right: 5px;
  font-size: 14px;
}

/* 状态图标 */
.status-icon {
  margin-right: 3px;
}

.dialog-content {
  padding: 20px;
}

.pwd-alert {
  margin-bottom: 20px;
}

.alert-content {
  margin-bottom: 10px;
}

.password-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 